local ClientOHOH = _G.ClientOHOH;
local M = ClientOHOH.class.new(script, ClientOHOH.files.Client_PlayerComponent(),script.Parent.Name);
local CallBackManager = ClientOHOH.load.CallBackManager();
local UIManager = ClientOHOH.load.UIManager();
local FunctionList = ClientOHOH.load.FunctionList();
local ui_list=UIManager().ui_list
local HomeGui=ui_list.HomeGui
-- local BuffGui=ui_list.BuffGui
local GlobalTipGui=ui_list.GlobalTipGui
-- local Buff_Cfg=ClientOHOH.config.Buff
local Mall_Cfg=ClientOHOH.config.Mall
local LanguageHelper=_G.LanguageHelper 
local gamePass_cfg = ClientOHOH.config.GamePass;
local MarketplaceService = game:GetService("MarketplaceService")
local gUserDataEvent=nil
local ShopGui_new=UIManager:CreateUI("ShopGui",require(script.ShopGui_new))
local diamondGui = ShopGui_new:Get("diamond")
local gamepassGui = ShopGui_new:Get("gamepass")
local limitedGui = ShopGui_new:Get("limited")
local potionsGui = ShopGui_new:Get("potions")
local winsGui = ShopGui_new:Get("wins")
local ConnectClass = _G.CommonOHOH.load.Connect()
local Good_Cfg=ClientOHOH.config.Goods
local Weapon_Cfg= _G.CommonOHOH.config.Weapon
local Diamond_Cfg = {}
local Gamepass_Cfg = {}
local Limited_Cfg = {}
local Potions_Cfg = {}
local Wins_Cfg = {}
local dataStore = nil
local oldLevel = nil
local ItemTool = _G.CommonOHOH.load.ItemTool()
local BigNumberHelper = ClientOHOH.load.BigNumberHelper()
local PetTool=_G.CommonOHOH.load.PetTool();

function M.new(self,...)
	return M(self,...);
end;

function M.ctor(self, parent)
	M.super.ctor(self, parent);
    self.player=self.parent
    CallBackManager:AddRbxConnect(self,HomeGui.insts.Shop.button.Activated, function()
        HomeGui:SetPositionRed()
        ShopGui_new:Show()
	end);

    dataStore = self.parent:GetComponent(ClientOHOH.load.Client_PlayerDataComponent())
    gUserDataEvent=self.parent.UserDataEvent
    oldLevel = dataStore:GetData("base").level
    --购买事件触发函数
    ShopGui_new.ShopBuyEvent:Connect(function(data)
        self:Buy(data)
    end)

    M:AddMallCfg()
    M.Init()
    self:AddConnect()
end;

function M.Init()
    table.sort(Diamond_Cfg,function(a,b)
        return a.id<b.id
    end)
    table.sort(Limited_Cfg,function(a,b)
        return a.id<b.id
    end)
    table.sort(gamePass_cfg,function(a,b)
        return a.id<b.id
    end)
    table.sort(Potions_Cfg,function(a,b)
        return a.id<b.id
    end)
    table.sort(Wins_Cfg,function(a,b)
        return a.id<b.id
    end)

    diamondGui.Full(Diamond_Cfg)
    gamepassGui.Full(Gamepass_Cfg)
    limitedGui.Full(Limited_Cfg)
    winsGui.Full(Wins_Cfg)
    potionsGui.Full(Potions_Cfg)
end

function M.AddConnect(self)
	--------------potions------------
	gUserDataEvent:Connect(function(data)
        if data["buff"] then
            for _,v in pairs(Potions_Cfg) do
                if #v.des == 1 then
                    v["had"]=ItemTool.GetItemCount(v["buffId"],dataStore)
                end
            end
            if not ShopGui_new:IsShowing() then
                HomeGui:SetPositionRed(1)
                potionsGui:SetPositionRed(1)
            end
            potionsGui.Update()
        end
    end)

    potionsGui.UseEvent:Connect(function(data)
        if data.had>0 then
            local buffId=data["buffId"]
            -- if self.parent:Invoke(FunctionList.use_buff,buffId) then
            --     -- BuffGui:CreatCellShow(data["buffId"],data.descArg)

            --     self.parent:GetComponent(_G.CommonOHOH.load.Common_BuffCtrl()):CreateBuff(buffId)
            -- else
            --     GlobalTipGui:Show(LanguageHelper:GetText(5))
            -- end

             if  not self.parent:GetComponent(_G.CommonOHOH.load.Common_BuffCtrl()):ClientCreateBuff(buffId) then
                -- BuffGui:CreatCellShow(data["buffId"],data.descArg)
                GlobalTipGui:Show(LanguageHelper:GetText(5))
                             
            end


        else
            GlobalTipGui:Show(LanguageHelper:GetText(30009))
        end
    end)

    --------------wins and diamond----------------
    gUserDataEvent:Connect(function(data)
        if  data["base"] and data["base"].level~=oldLevel then
            oldLevel=data["base"].level
            for _,v in pairs(Diamond_Cfg) do
                v:LevelChange(oldLevel)
            end
            for _,v in pairs(Wins_Cfg) do
                v:LevelChange(oldLevel)
            end
        end
    end)

    ------------gamepass------------
	gUserDataEvent:Connect(function(data)
        if data["gamePass"] then
            for name, v in pairs(data["gamePass"]) do
                for _, value in pairs(Gamepass_Cfg) do
                    if value.name == name then
                        value.isHad = true
                        break
                    end
                end
            end
            for _, value in pairs(Gamepass_Cfg) do
                if value["category"] then
                    value:SetHad(data["gamePass"])
                end
            end
            gamepassGui.UpdateGamePass(data["gamePass"])
        end
    end)
    
end


function M.AddMallCfg(self)
    for key, value in pairs(Mall_Cfg) do
        if value.belong == "gamepass" then
            self:AddGamePassCfg(value)
        else if value.belong == "diamond" then
            self:AddDiamondCfg(value)
        elseif value.belong == "wins" then
            self:AddWinsCfg(value)
        elseif value.belong == "potions" then
            self:AddPotionsCfg(value)
        else
            self:AddLimitedCfg(value)
        end    
        end
    end
end


--以下AddCfg函数传入的data都为单条Mall中的数据
function M.AddGamePassCfg(self,data)
    assert(Good_Cfg[data.gid],"不存在计费点:"..data.gid)
    data["price"] = Good_Cfg[data.gid].price
    data["buyInfo"] = {
        gid = Good_Cfg[data.gid].id,
        gType = Good_Cfg[data.gid].gType
    }
    data["goodData"] = Good_Cfg[data.gid]
    local gamePassData = dataStore:GetData("gamePass")
    local value = nil
    for k, v in pairs(Good_Cfg[data.gid].itemData) do
        value = typeof(v)
        data["name"] = k
    end

    if value ~= "number" then
        for _, value in pairs(Good_Cfg[data.gid].itemData) do
            data["category"] = string.split(value,",")
        end
        data["DataChange"]=ConnectClass.new()
        data["HadCount"]=0
        data["SetHad"]=function(this,gamePassData)
            local count=0
            for _,packItemId in pairs(data["category"]) do
                if gamePassData[packItemId] then
                    count=count+1
                end
            end
            this.HadCount=count
            if this.HadCount== #this.des then
                this["isHad"]=true
            else
                this["isHad"]=false
            end
            this.DataChange:Action(this["isHad"])
        end
        data:SetHad(dataStore:GetData("gamePass"))
    else
        data["DataChange"]=ConnectClass.new()
        for index, _ in pairs(Good_Cfg[data.gid].itemData) do
            if gamePassData[index] then
                data["isHad"] = true
            else
                data["isHad"] = false
            end
        end
    end
    table.insert(Gamepass_Cfg,data)
end

function M.AddDiamondCfg(self,data)
    assert(Good_Cfg[data.gid],"不存在计费点:"..data.gid)
    data["price"] = Good_Cfg[data.gid].price
    --用于购买的真正gid和type
    data["buyInfo"] = {
        gid = Good_Cfg[data.gid].id,
        gType = Good_Cfg[data.gid].gType
    }
    data["goodData"] = Good_Cfg[data.gid]
    data["DataChange"] = ConnectClass.new()
    data["LevelChange"] = function(this,level)
        local id,amount;
        for k, v in pairs(Good_Cfg[this.gid].itemData) do
           id = k
           amount = v 
        end
        local k,count = ItemTool.GetRewardByLevel(id,amount,level)
        this["title"] = "+"..BigNumberHelper:ToString(count)
        this.DataChange:Action()
    end
    data:LevelChange(dataStore:GetData("base").level)
    table.insert(Diamond_Cfg,data)
end

function M.AddWinsCfg(self,data)
    assert(Good_Cfg[data.gid],"不存在计费点:"..data.gid)
    data["price"] = Good_Cfg[data.gid].price
    data["buyInfo"] = {
        gid = Good_Cfg[data.gid].id,
        gType = Good_Cfg[data.gid].gType
    }
    --goodData一条商品数据
    data["goodData"] = Good_Cfg[data.gid]
    --用于界面ui更新
    data["DataChange"] = ConnectClass.new()
    data["LevelChange"] = function(this,level)
        local id,amount;
        for k, v in pairs(Good_Cfg[this.gid].itemData) do
           id = k
           amount = v 
        end
        local k,count = ItemTool.GetRewardByLevel(id,amount,level)
        this["title"] = "+"..BigNumberHelper:ToString(count)
        --触发dataChange事件，更新ui界面
        this.DataChange:Action()
    end
    data:LevelChange(dataStore:GetData("base").level)
    table.insert(Wins_Cfg,data)
end


function M.AddPotionsCfg(self,data)
    assert(Good_Cfg[data.gid],"不存在计费点:"..data.gid)
    data["price"] = Good_Cfg[data.gid].price
    data["buyInfo"] = {
        gid = Good_Cfg[data.gid].id,
        gType = Good_Cfg[data.gid].gType
    }
    data["goodData"] = Good_Cfg[data.gid]
    local itemLenght=0
    for k,v in pairs(Good_Cfg[data.gid].itemData) do
        itemLenght=itemLenght+1
    end
    if itemLenght>1 then
        local count = nil
        --药水包中药水的种类，是一个数组
        data["potionsCategory"] = {}
        -- for _, pTable in pairs(Good_Cfg[data.gid].itemData) do
        --     for pType, amount in pairs(pTable) do
        --         table.insert(data["potionsCategory"],pType)
        --         if count == nil then
        --             count = amount
        --         end
        --     end
        -- end

        for pType, amount in pairs(Good_Cfg[data.gid].itemData) do
            table.insert(data["potionsCategory"],pType)
            if count == nil then
                count = amount
            end
        end


        data["count"] =BigNumberHelper:ToString(count)
        --药水包中药水的效果时长，只规定了一个值
        -- data["timeArg"] = data.arg[2]
    else
        -- data["had"] = ItemTool.GetItemCount(data.item_id,dataStore)
        for pType, value in pairs(Good_Cfg[data.gid].itemData) do
            data["sellCount"] = value
            data["had"] = ItemTool.GetItemCount(pType,dataStore)
            data["buffId"] = pType
            local list = string.split(pType,"_")
            data["descArg"] = list[#list]
        end
    end
    table.insert(Potions_Cfg,data)
end


function M.AddLimitedCfg(self,data)
    -- assert(Good_Cfg[data.gid],"不存在计费点:"..data.gid)
    if data.belong == "limitedEgg" then
        data["DataChange"] = ConnectClass.new()
        local eggCfg= ItemTool.GetEggAllInfo(data.item_id)
        --egg概率从eggCfg中读,看itemTool中的GetEggAllInfo返回值
        data["egg"] = eggCfg
        data["priceX1"] = Good_Cfg[data.des[1]].price
        data["priceX3"] = Good_Cfg[data.des[2]].price
        data["priceX10"] = Good_Cfg[data.des[3]].price
        data["buyInfo"] = {
            {
                gid = Good_Cfg[data.des[1]].id,
                gType = Good_Cfg[data.des[1]].gType
            },
            {
                gid = Good_Cfg[data.des[2]].id,
                gType = Good_Cfg[data.des[2]].gType
            },
            {
                gid = Good_Cfg[data.des[3]].id,
                gType = Good_Cfg[data.des[3]].gType
            }
        }
    else if data.belong == "op" then
        data["price"] = Good_Cfg[data.gid].price
        data["buyInfo"] = {
            gid = Good_Cfg[data.gid].id,
            gType = Good_Cfg[data.gid].gType
        }
        --GetPetDataByPetId
        data["petData"] = PetTool.GetPetDataByPetId(data.item_id)
    else
        --weapon
        data["price"] = Good_Cfg[data.gid].price
        data["buyInfo"] = {
            gid = Good_Cfg[data.gid].id,
            gType = Good_Cfg[data.gid].gType
        }
        data["goodData"] = Good_Cfg[data.gid]
        local item_id = tonumber(data.item_id)
        data["power"] = Weapon_Cfg[item_id].damge
    end
    end
        table.insert(Limited_Cfg,data)
end

--购买Id，compent,fucId
--Buy(1001,"Common_RebirthCtrl","buyDone")
function M.Buy(self,data,compent,fucId)
    -- print("buy,gid:",data.gid,"  gtpe ",data.gType)
    self.player.RobuxBuyEvent:Action(data.gid)
end

function M.dtor(self)
	M.super.dtor(self);
end;

return M